import Vue from 'vue'
import { login } from '@/api/user-manager'
import router from '@/router/index.js'
const state = JSON.parse(window.localStorage.getItem('user')) || {}
const actions = {
  login({ commit }, user) {
    console.log('user :>> ', user)
    return new Promise((resolve, reject) => {
      login({
        loginName: user.username,
        loginPassword: window.btoa(user.password),
      })
        .then((res) => {
          if (res.success) {
            commit('LOGIN', res.data)
            resolve(user)
          } else {
            reject(res.message)
          }
        })
        .catch(() => {
          reject('网络错误')
        })
    })
  },
  logout({ commit }) {
    return new Promise((resolve) => {
      // 请求注销接口
      commit('LOGOUT')
      router.push('login')
      resolve()
    })
  },
}
const mutations = {
  LOGIN: (state, user) => {
    // 请求登录接口
    console.log('user :>> ', user)
    let curUser = {
      user,
      token: user.token,
    }
    Object.keys(curUser).forEach((i) => Vue.set(state, i, curUser[i]))
    // state = Object.assign(state, curUser)
    window.localStorage.setItem('user', JSON.stringify(curUser))
  },
  LOGOUT: (state) => {
    window.localStorage.removeItem('user')
    Object.keys(state).forEach((item) => Vue.delete(state, item))
  },
}
const getters = {
  user: (state) => {
    return state.user
  },
  token: (state) => {
    return state.token
  },
}
export default {
  // namespaced: true, // 带着命名空间导出
  state,
  getters,
  actions,
  mutations,
}
